<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      @close="handleClose"
      draggable
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>{{ title }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <el-form :model="editForm" :rules="rules" label-width="130px" ref="editFormRef">
        <!-- 基本信息 -->
        <div class="bg-white mt-[10px]">
          <BaseHead>基本信息</BaseHead>
          <div class="p-[10px]">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="申请人" prop="applyer">
                  <el-autocomplete
                    v-model="editForm.applyer"
                    :fetch-suggestions="queryApplyer"
                    clearable
                    placeholder="请输入检索关键词"
                    value-key="name"
                    highlight-first-item
                    @select="selectApplyer"
                    @blur="ApplyerBlur"
                    :disabled="verifyRoleType.isKyry()"
                  >
                    <template #default="{ item }">
                      <span>{{ item.name }}</span>
                      <span class="mx-[10px]">{{ item.account }}</span>
                      <span>{{ item.unitName }}</span>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申请时间" prop="applyTime">
                  <el-date-picker
                    v-model="editForm.applyTime"
                    type="date"
                    clearable
                    placeholder="请选择时间"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input placeholder="联系电话" clearable v-model="editForm.contactPhone">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属单位" prop="unitId">
                  <CommonTreeSelect
                    v-model="editForm.unitId"
                    valueKey="codeColumn"
                    labelKey="valueColumn"
                    paramsName="成果归属单位"
                    placeholder="请选择所属单位"
                    :disabled="verifyRoleType.isKyry()"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="服务类型" prop="serviceType">
                  <CommonSelect
                    v-model="editForm.serviceType"
                    valueKey="code"
                    paramsName="科研服务类型"
                    placeholder="请选择服务类型"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="上传申请材料" prop="fileId">
                      <FileUpload
                        :uploadUrl="uploadUrl"
                        v-model="fileList"
                        @change="fileChange"
                        exceedLimitType="disabled"
                        class="flex-1"
                      >
                        <el-link
                          class="ml-[30px]"
                          type="primary"
                          @click="handleDownTpl('科研服务申请材料模板.rar')"
                          >模板下载</el-link
                        >
                      </FileUpload>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button
              type="primary"
              @click="save(-1)"
              :loading="loading && submitType == -1"
              :disabled="loading && submitType != -1"
              >{{ verifyRoleType.isKyry() ? "暂存" : "保存" }}</el-button
            >
            <el-button
              type="primary"
              @click="save(1)"
              :loading="loading && submitType == 1"
              :disabled="loading && submitType != 1"
              v-if="verifyRoleType.isKyry()"
              >提交</el-button
            >
            <el-button
              type="primary"
              @click="save(2)"
              :loading="loading && submitType == 2"
              :disabled="loading && submitType != 2"
              v-if="
                verifyRoleType.iskycgly() &&
                (editForm.checkstatus == '' ||
                  [-1, 3].includes(Number(editForm.checkstatus)) ||
                  editForm.isAuditor)
              "
              >保存并通过</el-button
            >
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import { editRecords, recordsDetail } from "@/api/kyfw";
import { getPersonList } from "@/api/project/common";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonTreeSelect from "@/views/project/components/CommonTreeSelect.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import { ElMessage } from "element-plus";
import { assignObj, verifyRoleType, handleDownTpl } from "@/utils/main";
import { phoneReg } from "@/utils/validate";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const dialogVisible = ref(false);
const editFormRef = ref();
const operateId = ref(null);
const detailData = ref(null);
const loading = ref(false);
const submitType = ref(null);
const title = computed(() => {
  return operateId.value ? "科研服务编辑" : "科研服务新增";
});
const uploadUrl = `/commonFile/uploadFile?modelName=科研服务`;
const fileList = ref([]);
//基本信息表单
const editForm = reactive({
  applyer: "",
  applyerCode: "",
  applyTime: "",
  contactPhone: "",
  unitId: "",
  serviceType: "",
  fileId: "",
  isAuditor: false,
  taskId: "",
  checkstatus: "",
});
//表单验证规则
const rules = reactive({
  applyer: [
    {
      required: true,
      message: "申请人必填",
    },
  ],
  applyTime: [
    {
      required: true,
      message: "请选择申请时间",
    },
  ],
  contactPhone: [
    {
      pattern: phoneReg,
      message: "请输入正确的电话号码",
    },
  ],
  unitId: [
    {
      required: true,
      message: "所属单位必填",
    },
  ],
  fileId: [
    {
      required: true,
      message: "请上传申请材料",
    },
  ],
});
//获取数据详情
const getDetail = async () => {
  try {
    const res = await recordsDetail(operateId.value);
    detailData.value = res.data;
    const files = res.data.fileInfoList || [];
    fileList.value = files.map((item) => ({ id: item.fileId, name: item.filename }));
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = async () => {
  operateId.value = null;
  if (verifyRoleType.isKyry()) {
    editForm.applyer = userStore.nickName;
    editForm.applyerCode = userStore.userRealId;
    editForm.unitId = userStore.deptId;
    editForm.contactPhone = userStore.phonenumber;
  }
  dialogVisible.value = true;
};
// 编辑
const edit = async (id, isAuditor, taskId) => {
  operateId.value = id;
  dialogVisible.value = true;
  await getDetail();
  nextTick(() => {
    assignObj(editForm, detailData.value);
    editForm.isAuditor = isAuditor;
    editForm.taskId = taskId;
  });
};
defineExpose({ add, edit });
const emit = defineEmits(["save-success"]);
//搜索人员列表
const queryApplyer = async (queryString, cb) => {
  if (queryString.trim() == "") {
    return;
  }
  //输入时清空chargerCode结合blur事件，控制负责人必须是选择的下拉框的值
  editForm.applyerCode = "";
  const params = {
    name: queryString,
  };
  try {
    const res = await getPersonList(params);
    cb(res.data);
  } catch (error) {
    console.log(error);
  }
};
//选择申请人
const selectApplyer = (val) => {
  editForm.applyerCode = val.id;
  editForm.unitId = val.unitId;
  editForm.contactPhone = val.mobile;
};
//清空申请人字段的值
const resetApplyer = () => {
  editForm.applyerCode = "";
  editForm.applyer = "";
  editForm.unitId = "";
  editForm.contactPhone = "";
};
//选择申请人框失去焦点
const ApplyerBlur = () => {
  if (!editForm.applyerCode) {
    resetApplyer();
  }
};
//上传附件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  editForm.fileId = ids.join(",");
};
//点击保存
const save = async (type) => {
  submitType.value = type;
  try {
    await editFormRef.value?.validate(async (valid) => {
      if (valid) {
        let res;
        let params = {
          ...editForm,
          submitType: type,
        };
        loading.value = true;
        if (operateId.value) {
          params.id = operateId.value;
        }
        res = await editRecords(params);
        if (res.code === 200) {
          ElMessage({
            message: "操作成功！",
            type: "success",
          });
          dialogVisible.value = false;
          emit("save-success");
        }
      }
    });
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
//关闭弹窗
const handleClose = () => {
  editFormRef.value.resetFields();
  editForm.applyerCode = "";
  editForm.isAuditor = false;
  editForm.taskId = "";
  editForm.checkstatus = "";
  fileList.value = [];
};
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
</style>
